package data

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/redis/go-redis/v9"
	"time"
	"xgs_kratos/app/users/internal/biz"
	"xgs_kratos/app/users/internal/data/dal/entity"
	"xgs_kratos/gen/orders"
)

//data 层处理数据的存储和读取

type userRepo struct {
	data *Data
	log  *log.Helper
}

// NewUserRepo . r registry.Discovery,
func NewUserRepo(data *Data, logger log.Logger) biz.UserRepo {
	return &userRepo{
		data: data,
		log:  log.NewHelper(logger),
	}
}

// CreateUser 创建用户
func (r *userRepo) CreateUser(ctx context.Context, req *biz.User) (*biz.User, error) {
	user := entity.UsersMo{
		Age:   &req.Age,
		Name:  req.Name,
		Email: req.Email,
	}
	result := r.data.db.Create(&user)
	if result.Error != nil {
		return nil, result.Error
	}
	return &biz.User{
		Id:    result.RowsAffected,
		Age:   *user.Age,
		Name:  user.Name,
		Email: user.Email,
	}, nil
}

func (r *userRepo) ListUser(ctx context.Context, req *biz.User) ([]*biz.User, error) {
	//获取order服务的client
	client := r.data.orderClient
	order, err := client.CreateOrder(ctx, &orders.CreateOrderRequest{
		OrderNo: 1,
	})
	if err != nil {
		return nil, err
	}
	fmt.Println(order)
	var redisKey = "user_list"
	//获取redis的数据
	redisData, err := r.data.redisCli.Get(ctx, redisKey).Result()
	if err == redis.Nil {
		redisData = ""
	} else if err != nil {
		return nil, err
	}

	var results []entity.UsersMo
	//缓存没有查询到查询数据库
	if redisData == "" {
		fmt.Println("查询了数据库。。。。。。")
		res := r.data.db.Find(&results)
		if res.Error != nil {
			return nil, res.Error
		}
		//把数据转换成json
		resByte, err := json.Marshal(results)
		if err != nil {
			return nil, err
		}
		//设置redis数据
		err = r.data.redisCli.Set(ctx, redisKey, string(resByte), 30*time.Second).Err()
		if err != nil {
			return nil, err
		}
	} else {
		fmt.Println("查询的缓存。。。。。。")
		//查到之后 把数据转换回去
		err = json.Unmarshal([]byte(redisData), &results)
		if err != nil {
			return nil, err
		}
	}
	var userDatas []*biz.User
	for _, result := range results {
		userDatas = append(userDatas, &biz.User{
			Id:    int64(result.ID),
			Name:  result.Name,
			Age:   *result.Age,
			Email: result.Email,
		})
	}

	return userDatas, nil
}
